package cn.kgc.easybuy.controller;

import cn.kgc.easybuy.config.SftpUtilConfig;
import cn.kgc.easybuy.utils.AjaxResult;
import cn.kgc.easybuy.utils.SftpUtil;
import com.jcraft.jsch.SftpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Controller
public class BaseController {

    @Autowired
    private SftpUtil sftpUtil;

    protected AjaxResult uploadFile(AjaxResult ajaxResult, String errMsg, MultipartFile file){
        sftpUtil.login();

        String fileName=file.getOriginalFilename();

        //检验文件格式及大小
        String fileType= fileName.substring(fileName.lastIndexOf(".") + 1);
        String[] fileTypes={"jpg","png","jpeg","gif"};
        boolean flag=false;
        for (String type:fileTypes){
            if (fileType.equals(type)){
                flag=true;
                break;
            }
        }
        if (!flag){
            return ajaxResult.add(errMsg,"文件格式错误").add("code",5500);
        }

        if ((file.getSize()>1024*1024*2)){
            return ajaxResult.add(errMsg,"文件大于2MB").add("code",5500);
        }

        String newFileName= UUID.randomUUID().toString()+"."+fileType;
        try {
            //file.transferTo(new File(uploadDir,newFileName));
            sftpUtil.upload("/home/fyq/my-images/easybuyImages",newFileName,file.getInputStream());
            return ajaxResult.add("newFileName",newFileName).add("code",5200);
        } catch (IOException | SftpException e) {
            e.printStackTrace();
            return ajaxResult.add(errMsg,"文件上传失败").add("code",5500);
        }finally {
            sftpUtil.logout();
        }
    }
}
